from typing import List, Dict, Any
from loguru import logger
from app.core.platform_config import platform_config
from app.services.platform_auth import platform_auth
from app.utils.logger import log_exception

class PlatformSubscribe:
    """平台订阅服务"""
    
    @log_exception
    async def subscribe_dahua_events(self, event_types: List[str]) -> bool:
        """
        订阅大华平台事件
        
        event_types: 事件类型列表，例如：
        - AccessControl  # 门禁事件
        - Face          # 人脸识别事件
        - Alarm         # 报警事件
        """
        try:
            headers = await platform_auth.get_dahua_headers()
            callback_url = platform_config.get_dahua_callback_url()
            
            # 构建订阅数据
            data = {
                "callbackUrl": callback_url,
                "eventTypes": event_types,
                "subscribeId": "door_access_control",  # 订阅标识
                "subscribeType": "http",  # 订阅方式
                "subscribeLevel": 1  # 订阅级别：1-实时
            }
            
            # 发送订阅请求
            async with platform_auth.session.post(
                f"{platform_config.dahua.event_host}{platform_config.dahua.event_subscribe_path}",
                headers=headers,
                json=data
            ) as response:
                if response.status == 200:
                    result = await response.json()
                    if result.get("code") == 0:
                        logger.info(f"大华平台事件订阅成功: {event_types}")
                        return True
                        
                logger.error(f"大华平台事件订阅失败: {await response.text()}")
                return False
                
        except Exception as e:
            logger.error(f"大华平台事件订阅异常: {str(e)}")
            return False
            
    @log_exception
    async def subscribe_hikvision_events(self, event_types: List[str]) -> bool:
        """
        订阅海康平台事件
        
        event_types: 事件类型列表，例如：
        - FACE_MATCH      # 人脸比对事件
        - ACCESS_CONTROL  # 门禁事件
        - ALARM          # 报警事件
        """
        try:
            headers = await platform_auth.get_hikvision_headers()
            callback_url = platform_config.get_hikvision_callback_url()
            
            # 构建订阅数据
            data = {
                "eventTypes": event_types,
                "callbackUrl": callback_url,
                "eventLevel": 0,  # 0-所有级别
                "subscribeId": "door_access_control",  # 订阅标识
                "subscribeDetail": {
                    "callbackProtocol": "http",
                    "callbackContentType": "application/json",
                    "eventRetryCount": 3,  # 失败重试次数
                    "eventRetryInterval": 5  # 重试间隔（秒）
                }
            }
            
            # 发送订阅请求
            async with platform_auth.session.post(
                f"{platform_config.hikvision.event_host}{platform_config.hikvision.event_subscribe_path}",
                headers=headers,
                json=data
            ) as response:
                if response.status == 200:
                    result = await response.json()
                    if result.get("code") == "0":
                        logger.info(f"海康平台事件订阅成功: {event_types}")
                        return True
                        
                logger.error(f"海康平台事件订阅失败: {await response.text()}")
                return False
                
        except Exception as e:
            logger.error(f"海康平台事件订阅异常: {str(e)}")
            return False
            
    @log_exception
    async def unsubscribe_dahua_events(self, event_types: List[str]) -> bool:
        """取消订阅大华平台事件"""
        try:
            headers = await platform_auth.get_dahua_headers()
            
            # 构建取消订阅数据
            data = {
                "eventTypes": event_types,
                "subscribeId": "door_access_control"  # 与订阅时使用的标识一致
            }
            
            # 发送取消订阅请求
            async with platform_auth.session.post(
                f"{platform_config.dahua.event_host}{platform_config.dahua.event_unsubscribe_path}",
                headers=headers,
                json=data
            ) as response:
                if response.status == 200:
                    result = await response.json()
                    if result.get("code") == 0:
                        logger.info(f"大华平台事件取消订阅成功: {event_types}")
                        return True
                        
                logger.error(f"大华平台事件取消订阅失败: {await response.text()}")
                return False
                
        except Exception as e:
            logger.error(f"大华平台事件取消订阅异常: {str(e)}")
            return False
            
    @log_exception
    async def unsubscribe_hikvision_events(self, event_types: List[str]) -> bool:
        """取消订阅海康平台事件"""
        try:
            headers = await platform_auth.get_hikvision_headers()
            
            # 构建取消订阅数据
            data = {
                "eventTypes": event_types,
                "subscribeId": "door_access_control"  # 与订阅时使用的标识一致
            }
            
            # 发送取消订阅请求
            async with platform_auth.session.post(
                f"{platform_config.hikvision.event_host}{platform_config.hikvision.event_unsubscribe_path}",
                headers=headers,
                json=data
            ) as response:
                if response.status == 200:
                    result = await response.json()
                    if result.get("code") == "0":
                        logger.info(f"海康平台事件取消订阅成功: {event_types}")
                        return True
                        
                logger.error(f"海康平台事件取消订阅失败: {await response.text()}")
                return False
                
        except Exception as e:
            logger.error(f"海康平台事件取消订阅异常: {str(e)}")
            return False

# 创建全局订阅服务实例
platform_subscribe = PlatformSubscribe() 